package com.design.pattern.proxy.aop;

import com.design.pattern.proxy.RealSubject;
import com.design.pattern.proxy.Subject;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Projectname: design-pattern
 * @Filename: JdkProxy
 * @Author: FANSEA
 * @Date:2024/11/4 15:06
 */
public class JdkProxy {
    public static void main(String[] args) {
        Subject realSubject = new RealSubject();
        Subject proxyInstance = (Subject) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(),
                realSubject.getClass().getInterfaces(), new MyInvocationHandler(realSubject));
        proxyInstance.request();
        proxyInstance.response();
    }
    static class MyInvocationHandler implements InvocationHandler {
        Subject subject;
        public MyInvocationHandler(Subject realSubject) {
            this.subject = realSubject;
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("连接数据库成功!");
            method.invoke(subject, args);
            System.out.println("释放连接！");
            return null;
        }
    }

}
